$(function(){
  // Prefecture Model
  // ----------------

  window.Prefecture = Backbone.Model.extend({
    initialize: function(){
      // 名前の初期化
      if(!this.get("name")) this.set({name: "NONE"});
      // 人口の初期化
      if(!this.get("population")) this.set({population: -1});
      // 面積の初期化
      if(!this.get("area")) this.set({area: -1});
    }
  });

  // Prefecture Collection
  // ---------------------
  window.Prefectures = Backbone.Collection.extend({
    model: Prefecture,
    localStorage: new Store("iw2011graphdemo")

  });

  // Create our global collection of Prefectures.
  window.prefs = new Prefectures;

  // Switch to alternate column
  // (radio button)
  // --------------------------
  window.SwitchView = Backbone.View.extend({
    el: "#switchview",

    events: {
      "click #switchview input": "switchCol"
    },
    initialize: function(){
      _.bindAll(this, "switchCol");
    },
    switchCol: function(){
      var self = this;
      this.$("input").each(function(){
        if($(this).attr("checked")) {
          self.trigger("change", $(this).val());
          return;
        }
      });
    }
  });
  window.swi = new SwitchView;

  // Graph View
  // ------------------
  window.GraphView = Backbone.View.extend({
    el: "#graphview",
    initialize: function(){
      this.canvas = $(this.el+" canvas")[0];
      this.context = this.canvas.getContext("2d");
      this.w = this.canvas.width; this.h = this.canvas.height;
      this.col = "population";

      _.bindAll(this, "render", "changeCol");
      prefs.bind("all", this.render);
      swi.bind("change", this.changeCol);
    },

    changeCol: function(col){
      this.col = col;
      this.render();
    },

    render: function(){
      var col_ = this.col;
      var datas_ = prefs.map(function(pref){ return pref.attributes[col_]; });
      var max_ = _.max(datas_);

      var len_ = prefs.length;
      var pad_ = 15;
      var dx_ = (this.w) / len_;
      var w_ = dx_ - 2*pad_;
      var h_ = this.h / max_;

      this.context.clearRect(0,0,this.w, this.h);
      this.context.fillStyle = 'blue';

      for(var i = 0, l = datas_.length; i < l; ++i){
        this.context.fillRect( dx_ * i + pad_, this.h - h_ * datas_[i], w_, h_*datas_[i]);
      }

      this.context.beginPath();
      this.context.moveTo(0, this.h);
      this.context.lineTo(0, 0);
      this.context.moveTo(0, this.h);
      this.context.lineTo(this.w, this.h);
      this.context.stroke();
      this.context.closePath();
    }
  });
  // globally accessible graph view object.
  window.graph = new GraphView;

  // Table row view
  // ---------------
  window.rowView = Backbone.View.extend({
    tagName: "tr",
    template: _.template("<td><%= name %></td><td data-attr='population' contenteditable><%= population %></td><td data-attr='area' contenteditable><%= area %></td>"),

    events:{'blur td':'onBlur'},
    initialize: function() {
      _.bindAll(this, 'render', 'onBlur');
      this.model.bind('change', this.render);
      this.model.view = this;
    },
    render: function(){
      $(this.el).html(this.template(this.model.toJSON()));
      return this;
    },
    onBlur: function(e){
      var el_ = $(e.target);

      var attr_ = el_.attr("data-attr");
      var val_ = el_.text();
      var obj_ = {}; obj_[attr_] = val_;
      this.model.save(obj_);
    }
  });


  // TableView
  // --------------------
  window.TableView = Backbone.View.extend({
    el: "#tableview",

    template: _.template($('#table-template').html()),

    events: {
    },

    initialize: function(){
      _.bindAll(this, "render");

      prefs.bind("refresh", this.render);
      prefs.fetch();
    },

    render: function(){
      prefs.each(function(pref){
        var view = new rowView({model:pref});
        this.$("tbody").append(view.render().el);
      });
    }

  });
  
  window.tbl = new TableView;
});
